// @Author EthanScriptOn
// @Desc
package config_processor_management

import (
	"errors"
	"gitee.com/fatzeng/srf_switch_basic_components/processor"
	"gitee.com/fatzeng/srf_switch_basic_components/resource"
	"gitee.com/fatzeng/srf_switch_config/config_source_loader_management"
)

type SimpleFreightProcessorManager struct {
	resourceManager *resource.ResourceManager
}

func (s *SimpleFreightProcessorManager) CreateProcessor() error {
	freighter, err := config_source_loader_management.GetSupportedFreighter()
	if err != nil {
		return err
	}
	processor, err := processor.MakeProcessor(freighter)
	if err != nil {
		return err
	}
	if err = processor.Initialization(); err != nil {
		return err
	}
	_, err, isAdded := s.resourceManager.AddResource(FreightIdentifier, processor)
	if !isAdded {
		return errors.New("resource resource add resource fail")
	}
	return err
}

func (s *SimpleFreightProcessorManager) RemoveProcessor(processorKey interface{}) error {
	identifier := processorKey
	_, err, _ := s.resourceManager.DelResource(identifier)
	return err
}

func (s *SimpleFreightProcessorManager) GetAppropriateProcessor(processorKey interface{}) (processor.Processor, error) {
	return s.GetProcessor(processorKey)
}

func (s *SimpleFreightProcessorManager) GetProcessor(processorKey interface{}) (processor.Processor, error) {
	identifier := processorKey
	resourceProcessor, err, hasResourceProcessor := s.resourceManager.GetResource(identifier)
	if !hasResourceProcessor {
		return nil, errors.New("processor resource not found resource processor")
	}
	if err != nil {
		return nil, err
	}
	resourceProcessorInstance, ok := resourceProcessor.(processor.Processor)
	if !ok {
		return nil, errors.New("resource processor type error")
	}
	return resourceProcessorInstance, nil
}
